﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.Office.Interop.Word;
using Microsoft.Office.Core;
using System.Collections.ObjectModel;

namespace DataProcess
{
    public partial class frmColor : Form
    {
        public frmColor()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (colorDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox1.BackColor = colorDialog1.Color;
                
                Color backColor = colorDialog1.Color;
                int ret = (int)(backColor.R * 0.299 + backColor.G * 0.587 + backColor.B * 0.114);
                Color forceColor = Color.FromArgb(ret, ret, ret);
                var brightness = forceColor.GetBrightness();
                if (brightness < 0.5)
                {
                    textBox1.ForeColor = Color.White;
                    textBox3.ForeColor = Color.White;
                }
                else
                {
                    textBox1.ForeColor = Color.Black;
                    textBox3.ForeColor = Color.Black;
                }
                textBox3.BackColor = forceColor;
                textBox2.Text = brightness.ToString();

            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (colorDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox1.ForeColor = colorDialog1.Color;
            }
        }

        public float[] hsb2rgb(float[] hsb)
        {

            float[] rgb = new float[3];

            //先令饱和度和亮度为100%，调节色相h  

            for (int offset = 240, i = 0; i < 3; i++, offset -= 120)
            {

                //算出色相h的值和三个区域中心点(即0°，120°和240°)相差多少，然后根据坐标图按分段函数算出rgb。但因为色环展，红色区域的中心点是0°同时也是360°，不好算，索性将三个区域的中心点都向右平移到240°再计算比较方便  

                float x = Math.Abs((hsb[0] + offset) % 360 - 240);

                //如果相差小于60°则为255  

                if (x <= 60) rgb[i] = 255;

                //如果相差在60°和120°之间，  

                else if (60 < x && x < 120) rgb[i] = ((1 - (x - 60) / 60) * 255);

                //如果相差大于120°则为0  

                else rgb[i] = 0;

            }

            //在调节饱和度s  

            for (int i = 0; i < 3; i++)

                rgb[i] += (255 - rgb[i]) * (1 - hsb[1]);

            //最后调节亮度b  

            for (int i = 0; i < 3; i++)

                rgb[i] *= hsb[2];

            return rgb;

        }

        private int Get180(int val, int max)
        {
            int ret = val + max / 2;
            if (ret > max)
            {
                ret = ret - max;
            }
            return ret;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            string path = @"D:\PASS组替换中药文本";
            string outPath = @"D:\PASS中药文本处理后";
            if (!Directory.Exists(outPath))
            {
                Directory.CreateDirectory(outPath);
            }
            string[] files = Directory.GetFiles(path, "*.txt");
            foreach (string file in files)
            {
                string content = File.ReadAllText(file, Encoding.Default);
                content = Regex.Replace(content, "【(方解|参考文献|国外资料汇编)】[^【]*", string.Empty);
                File.WriteAllText(Path.Combine(outPath, Path.GetFileName(file)), content, Encoding.Default);
            }
            MessageBox.Show("完成！");
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            string docPath = @"E:\说明书测试\20130619重庆市第九人民医院说明书";
            string tempPath = Path.Combine(docPath, "temp");
            if (!Directory.Exists(tempPath))
            {
                Directory.CreateDirectory(tempPath);
            }
            string[] flags = { "img", "table", "sub", "sup", "tr", "td" };
            string[] docFiles = Directory.GetFiles(docPath, "*.doc?");
            foreach (string docFile in docFiles)
            {
                var doc = app.Documents.Open(docFile);
                string htmlFile = Path.Combine(tempPath, Path.GetFileNameWithoutExtension(docFile) + ".html");
                doc.WebOptions.Encoding = MsoEncoding.msoEncodingSimplifiedChineseGBK;
                doc.SaveAs2(FileName: htmlFile, FileFormat: WdSaveFormat.wdFormatHTML);
                doc.Close();
                string content = File.ReadAllText(htmlFile, Encoding.Default);

                var htmlMatch = Regex.Match(content, "<body[^>]*>(.*)</body>", RegexOptions.Singleline);
                if (!htmlMatch.Success)
                {
                    throw new HtmlException("无法读取Html内容");
                }
                content = htmlMatch.Groups[1].Value;
                content = Regex.Replace(content, "<(/?[^<> \\r\\n]+)(\\s|\\r\\n)*.*?>", match =>
                {
                    //Debug.WriteLine(match.Groups[1].Value);

                    if (match.Groups[1].Value == "/p" || match.Groups[1].Value == "/div")
                    {
                        //return "<br />";
                    }
                    if (Array.IndexOf(flags, match.Groups[1].Value.TrimStart('/')) == -1)
                    {
                        return string.Empty;
                    }
                    if (match.Groups[1].Value == "img")
                    {
                        return Regex.Replace(match.Value, "<img[\\s|\\r\\n]+.*?(src=\"+.*?\"+).*?>", "<img $1 />", RegexOptions.Singleline);
                    }
                    else
                    {
                        return string.Format("<{0}>", match.Groups[1].Value);
                    }
                    //return match.Value;
                }, RegexOptions.Singleline);
                content = Regex.Replace(content, "^\\s*$\n", string.Empty, RegexOptions.Multiline);
                Regex ph = new Regex("【([^】]*)】");
                Match pMatch = ph.Match(content);
                int lastIndex = 0;
                PackageInsert pi = new PackageInsert();
                pi.Title = "";
                pi.Paragraphs = new Collection<PackageInsertParagraph>();
                while (pMatch.Success)
                {
                    if (pMatch.Index > lastIndex)
                    {
                        if (pi.Paragraphs.Count == 0)
                        {
                            pi.Paragraphs.Add(new PackageInsertParagraph { Title = "其他内容", Number = pi.Paragraphs.Count + 1, Content = ConvertToHtml(content.Substring(lastIndex, pMatch.Index - lastIndex)) });
                        }
                        else
                        {
                            var LastPh = pi.Paragraphs[pi.Paragraphs.Count - 1];
                            string phContent = content.Substring(lastIndex, pMatch.Index - lastIndex);

                            if (LastPh.Title == "药品名称")
                            {
                                Match names = Regex.Match(phContent, "(?<=^(通用名称|通用名|品名)(：|:)).*$", RegexOptions.Multiline);
                                if (names.Success)
                                {
                                    LastPh.Content = names.Value;
                                }
                                names = Regex.Match(phContent, "(?<=^(商品名称|商品名|英文商品名)(：|:)).*$", RegexOptions.Multiline);
                                if (names.Success)
                                {
                                    pi.Paragraphs.Add(new PackageInsertParagraph { Title = "商品名称", Content = names.Value });
                                }
                                names = Regex.Match(phContent, "(?<=^(英文名称|英文名)(：|:)).*$", RegexOptions.Multiline);
                                if (names.Success)
                                {
                                    pi.Paragraphs.Add(new PackageInsertParagraph { Title = "英文名称", Content = names.Value });
                                }
                                names = Regex.Match(phContent, "(?<=^(汉语拼音|汉语拼音名|拼音名)(：|:)).*$", RegexOptions.Multiline);
                                if (names.Success)
                                {
                                    pi.Paragraphs.Add(new PackageInsertParagraph { Title = "汉语拼音", Content = names.Value });
                                }
                                //药品名称：通用名称、通用名、品名
                                //商品名称：商品名称、商品名、英文商品名
                                //英文名称：英文名称、英文名
                                //汉语拼音：汉语拼音、汉语拼音名、拼音名

                            }
                            else
                            {
                                LastPh.Content = ConvertToHtml(phContent);
                            }

                        }
                    }
                    pi.Paragraphs.Add(new PackageInsertParagraph { Title = pMatch.Groups[1].Value });
                    lastIndex = pMatch.Index + pMatch.Value.Length;
                    pMatch = pMatch.NextMatch();
                }
                if (lastIndex <= content.Length - 1)
                {
                    pi.Paragraphs[pi.Paragraphs.Count - 1].Content = ConvertToHtml(content.Substring(lastIndex, content.Length - 1 - lastIndex));
                }

                File.WriteAllText(Path.Combine(tempPath, Path.GetFileNameWithoutExtension(docFile) + ".txt"), content);
            }
            app.Quit();
            MessageBox.Show("完成！");
        }

        /// <summary>
        /// 转换文本中的换行符到html换行符，替换内容前后的换行符
        /// </summary>
        /// <param name="content">文本内容</param>
        /// <returns></returns>
        public string ConvertToHtml(string content)
        {
            content = content.Trim('\r', '\n', ' ');
            StringBuilder builder = new StringBuilder();
            Regex table = new Regex("<table.*?>.*?</table>", RegexOptions.Singleline);
            var hMatch = table.Match(content);
            int lastIndex = 0;
            while (hMatch.Success)
            {
                builder.Append(content.Substring(lastIndex, hMatch.Index - lastIndex).Replace("\r\n", "<br />"));
                builder.Append(Regex.Replace(hMatch.Value, "(?<=<td>)(.*?)(?=</td>)", match =>
                {
                    return match.Value.Trim('\r', '\n', ' ').Replace("\r\n", "<br />");
                }, RegexOptions.Singleline));
                lastIndex = hMatch.Index + hMatch.Value.Length;
                hMatch = hMatch.NextMatch();
            }
            if (lastIndex < content.Length)
            {
                builder.Append(content.Substring(lastIndex, content.Length - lastIndex).Trim('\r', '\n', ' ').Replace("\r\n", "<br />"));
            }

            return builder.ToString();
        }
    }



    public class PackageInsert
    {
        /// <summary>
        /// 说明书标题
        /// </summary>
        public string Title { get; set; }
        public Collection<PackageInsertParagraph> Paragraphs { get; set; }
    }

    public class PackageInsertParagraph
    {
        /// <summary>
        /// 段落顺序
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// 段落内容
        /// </summary>
        public string Content { get; set; }

        /// <summary>
        /// 段落序号
        /// </summary>
        public int Number { get; set; }
    }

    /// <summary>
    /// 通过Word转换来的HTML无法找到body标签，或者body标签不成对的异常
    /// </summary>
    public class HtmlException : System.SystemException
    {
        public HtmlException()
        {

        }
        public HtmlException(string message)
            : base(message)
        {

        }

        public HtmlException(string message, Exception innerException)
            : base(message, innerException)
        {

        }
        public override string Message
        {
            get
            {
                return base.Message;
            }
        }
    }
}
